/*
 * Copyright:  2018 smarabbit studio.
 *
 *  Licensed under the Confluent Community License; you may not use this file
 *  except in compliance with the License.  You may obtain a copy of the License at
 *
 *  http://www.confluent.io/confluent-community-license
 *
 *  Unless required by applicable law or agreed to in writing, software
 *  distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
 *  WARRANTIES OF ANY KIND, either express or implied.  See the License for the
 *  specific language governing permissions and limitations under the License.
 *
 *  @作   者： 黄开晖 (117227773@qq.com)
 *  @日   期:  2020年9月12日
 */
package com.massyframework.beanskin.runtime.framework.installing.strategy;

import java.util.Collection;
import java.util.Collections;
import java.util.HashSet;
import java.util.Objects;
import java.util.Set;
import java.util.concurrent.CopyOnWriteArraySet;
import java.util.function.Consumer;

import com.massyframework.beanskin.Module;
import com.massyframework.beanskin.service.Filter;
import com.massyframework.beanskin.service.ServiceRegistedEvent;
import com.massyframework.beanskin.service.ServiceRepository;
import com.massyframework.beanskin.service.ServiceUnregistingEvent;
import com.massyframework.beanskin.service.awaitstrategy.AwaitServiceDescriptor;
import com.massyframework.beanskin.service.awaitstrategy.AwaitStrategy;
import com.massyframework.beanskin.service.awaitstrategy.AwaitStrategyBuilder;
import com.massyframework.beanskin.util.classloading.ClassLoaderUtils;


/**
 * 缺省的等待策略
 * 
 * @author huangkh
 *
 */
final class DefaultAwaitStrategy implements AwaitStrategy{
		
	private Module<?> module;
	private Set<AwaitServiceDescriptor<?>> dependencies;
	private Set<AwaitServiceDescriptor<?>> unmatched;
	private Consumer<ServiceRepository> action;
	private boolean doIt = false;

	/**
	 * 
	 */
	protected DefaultAwaitStrategy(Builder builder) {
		this.module = Objects.requireNonNull(builder.module, "\"module\" cannot be null.");
		this.action = Objects.requireNonNull(builder.action, "\"action\" cannot be null.");
		
		if (builder.dependencyBuilders == null) {
			this.dependencies = Collections.emptySet();
			this.unmatched = Collections.emptySet();
		}else {
			this.dependencies = new HashSet<>();
			ServiceRepository repo = ServiceRepository.retrieveFrom(this.module);
			for (DefaultAwaitServiceDescriptor.Builder<?> depBuilder: builder.dependencyBuilders) {
				depBuilder.serviceRepository(repo);
				this.dependencies.add(depBuilder.build());
			}
			this.unmatched = new CopyOnWriteArraySet<>(this.dependencies);
		}
	}
	
	/**
	 * 模块
	 * @return {@link ServiceExportableModule}
	 */
	@Override
	public Module<?> getModule() {
		return this.module;
	}
	
	/**
	 * 所有等待服务描述
	 * @return {@link Set}
	 */
	@Override
	public Collection<AwaitServiceDescriptor<?>> getAwaitServiceDescriptors(){
		return Collections.unmodifiableCollection(this.dependencies);
	}

	
	@Override
	public Collection<AwaitServiceDescriptor<?>> getUnmatchs() {
		return Collections.unmodifiableCollection(this.unmatched);
	}

	/**
	 * 消费行为
	 * @return {@link Consumer}
	 */
	public Consumer<ServiceRepository> getAction() {
		return action;
	}
	
	/**
	 * 是否存有依赖服务
	 * @return
	 */
	public boolean isAllMatch() {
		if (this.unmatched.isEmpty()) return true;
		
		ServiceRepository repo = ServiceRepository.retrieveFrom(this.module);
		for (AwaitServiceDescriptor<?> entry: this.dependencies) {
			if (repo.findServiceReference(
					entry.getRequiredType(), 
					((DefaultAwaitServiceDescriptor<?>)entry).getFilter()).isPresent()) {
				this.unmatched.remove(entry);
			}
		}
		return this.unmatched.isEmpty();
	}
		
	/**
	 * 判断服务是否全部匹配
	 * @param event {@link ServiceRegistedEvent},服务注册事件
	 * @return {@link boolean},所有依赖均匹配则返回true.
	 */
	public boolean matchedAll(ServiceRegistedEvent<?> event) {		
		Class<?>[] serviceTypes = event.getServiceReference().getExportTypes();
		AwaitServiceDescriptor<?> found = null;
		for (AwaitServiceDescriptor<?> dependency: this.unmatched) {
			if (!this.serviceTypeIsMatch(serviceTypes, dependency)) {
				continue;
			}
			
			Filter filter = ((DefaultAwaitServiceDescriptor<?>)dependency).getFilter();
			if (filter.match(event.getServiceReference())) {
				found = dependency;
				break;
			}
		}
		
		if (found != null) {
			this.unmatched.remove(found);
		}
		
		return this.unmatched.isEmpty();
	}
	
	/**
	 * 服务取消注册事件处理
	 * @param event {@link ServiceUnregistingEvent}
	 */
	public void onServiceUnregisting(ServiceUnregistingEvent<?> event) {
		Class<?>[] serviceTypes = event.getServiceReference().getExportTypes();		
		for (AwaitServiceDescriptor<?> dependency: this.dependencies) {
			if (!this.serviceTypeIsMatch(serviceTypes, dependency)) {
				continue;
			}
			
			Filter filter =  ((DefaultAwaitServiceDescriptor<?>)dependency).getFilter();
			if (filter.match(event.getServiceReference())) {
				this.unmatched.add(dependency);
			}
		}
	}
	
	public synchronized void doAction() {
		if (this.doIt) return;
		this.doIt = true;
		
		ClassLoader contextLoader = ClassLoaderUtils.setThreadContextClassLoader(this.module.getModuleClassLoader());
		try {
			ServiceRepository repo = ServiceRepository.retrieveFrom(this.module);
			this.action.accept(repo);
		}finally {
			Thread.currentThread().setContextClassLoader(contextLoader);
		}
	}
	
	protected boolean serviceTypeIsMatch(Class<?>[] serviceTypes, AwaitServiceDescriptor<?> dependency) {
		for (Class<?> serviceType : serviceTypes) {
			if (serviceType == dependency.getRequiredType()) {
				return true;
			}
		}
		return false;
	}
	
		
	/**
	 * 创建构建器
	 * @param classLoader {@link ClassLoader},执行消费行为时的线程上下文类加载器
	 * @return {@link Builder}
	 */
	public static Builder newBuilder(Module<?> module) {
		return new Builder(module);
	}

	/**
	 * 构建器
	 * @author huangkh
	 *
	 */
	public static class Builder implements AwaitStrategyBuilder {
		
		private Module<?> module;
		private Set<DefaultAwaitServiceDescriptor.Builder<?>> dependencyBuilders;	
		private Consumer<ServiceRepository> action;
		

		/**
		 * 
		 */
		protected Builder(Module<?> module) {
			this.module = Objects.requireNonNull(module, "\"module\" cannot be null.");
		}

		@Override
		public Builder addDependencyService(Class<?> requiredType) {
			if (requiredType != null) {
				if (this.dependencyBuilders == null) {
					this.dependencyBuilders = new CopyOnWriteArraySet<>();
				}
				
				this.dependencyBuilders.add( 
						createAwaitServiceDescriptorBuilder(requiredType, null));
			}
			return this;
		}

		@Override
		public Builder addDependencyService(Class<?> requiredType, String filterString) {
			if (requiredType != null) {
				if (this.dependencyBuilders == null) {
					this.dependencyBuilders = new HashSet<>();
				}
				
				this.dependencyBuilders.add(
						createAwaitServiceDescriptorBuilder(requiredType, filterString));
			}
			return this;
		}
		
		private <T> DefaultAwaitServiceDescriptor.Builder<T> createAwaitServiceDescriptorBuilder(
				Class<T> requireType, String filterString){
			DefaultAwaitServiceDescriptor.Builder<T> result =
					DefaultAwaitServiceDescriptor.newBuilder();
			result.requiredType(requireType)
				.filterString(filterString);
			return result;
		}

		@Override
		public Builder action(Consumer<ServiceRepository> value) {
			this.action = value;
			return this;
		}
				
		public DefaultAwaitStrategy build() {
			return new DefaultAwaitStrategy(this);
		}
	}

}
